<template>
  <div>
    <div>
      <van-nav-bar title="黑马头条-登录" placeholder :fixed='true'/>
    </div>
    <div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="from.mobile"
          name="mobile"
          label="用户名"
          placeholder="用户名"
          :rules="[
            {
              required: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '请填写用户名',
            },
          ]"
        />
        <van-field
          v-model="from.code"
          type="password"
          name="code"
          label="密码"
          placeholder="密码"
          :rules="[
            { required: true, pattern: /^\d{6}$/, message: '请填写密码' },
          ]"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
          :disabled='islogin'
          :loading='islogin'
          loading-text="加载中..."
            >提交</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { setToken } from '@/utils/token'
import { loginAPI } from '@/api'
import { Notify } from 'vant'
export default {
  data () {
    return {
      from: {
        mobile: '13811111111',
        code: '246810'
      },
      islogin: false// 加载状态
    }
  },
  methods: {
    async onSubmit (values) {
      // console.log('submit', values)
      this.islogin = true
      try {
        const res = await loginAPI({ ...this.from })
        // this.$toast('登录成功')
        // 成功通知
        Notify({ type: 'success', message: '登录成功' })
        this.islogin = false
        console.log(res)
        // 把token存到本地
        setToken(res.data.data.token)
        this.$router.replace('/layout')
      } catch (err) {
        console.error(err)
        // 失败通知
        Notify({ type: 'danger', message: '登录失败' })
        this.islogin = true
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
